import {
  query,
  queryPipe,
  queryDesignPipe,
  queryWater,
  queryWorkstations1,
  queryAppendageCharac,
  queryHolecover,
  queryReducevalve,
} from '@/services/pipe_home';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import find from 'lodash/find';
import moment from 'moment';
import {
  message,
} from 'antd';


import { get as getProjection } from 'ol/proj'
import { getTopLeft, getWidth } from 'ol/extent'
import TileGrid from 'ol/tilegrid/TileGrid'
const projection = getProjection('EPSG:3857')
const matrixIds = []
const tileSizePixels = 256
const tileSizeMtrs = getWidth(projection.getExtent()) / tileSizePixels
const resolutions = []
for (let i = 0; i <= 18; i++) {
  matrixIds[i] = i
  resolutions[i] = tileSizeMtrs / Math.pow(2, i)
}
const tileGrid = new TileGrid({
  origin: getTopLeft(projection.getExtent()),
  resolutions: resolutions,
  matrixIds: matrixIds,
})



export default {
  namespace: 'pipe_home',
  state: {
    pageLoaded: false,
    bore: '全部',
    data: [],
    pipeData: {},
    pipeLength: 0,
    pipeCount: 0,
    waterData: [],
    Workstations1Data: [],
    designPipeData: {},
    holeCover: {},
    reduceValve: {},
    searchParams: {},
    mapType: 'sensing',
    showMapType: true,
    pressVisiable: true,
    pipeVisiable: true,
    designPipeVisiable: true,
    holeCoverVisiable: true,
    reduceValveVisiable: true,
    waterVisiable: true,
    workstations1Visiable: true,
    designCheckedKeys: ['design1'],
    appendageCheckedKeys: [],//附属物
    characteristicCheckedKeys: [],//特征
    zoom: 14,
    pointData: {},
    waterPointData: {},
    workstations1PointData: {},
    center: [89.21655514667722, 42.96389386391127],
    layers: [
      new TileLayer({
        title: '天地图卫星影像',
        visible: true,
        source: new XYZ({
          url: 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
          // url: 'https://tiles1.geovisearth.com/base/v1/img/{z}/{x}/{y}?format=webp&tmsIds=w&token=6dd3767b369eb5b724937e4ad74b2e78e95ad67ac7bbc1049539cb0691ad6ca2',
          // tileGrid: tileGrid, // 指定切片的网格参数
        }),
      }),
      new TileLayer({
        title: '天地图矢量图',
        visible: false,
        source: new XYZ({
          url: 'http://t3.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
          // tileGrid: tileGrid, // 指定切片的网格参数
        }),
      }),
      new TileLayer({
        title: '卫星标注',
        visible: true,
        source: new XYZ({
          url: 'http://t4.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
          // url: 'https://tiles1.geovisearth.com/base/v1/cia/{z}/{x}/{y}?format=png&tmsIds=w&token=6dd3767b369eb5b724937e4ad74b2e78e95ad67ac7bbc1049539cb0691ad6ca2',
          // tileGrid: tileGrid, // 指定切片的网格参数
        }),
      }),
      new TileLayer({
        title: '矢量图标注',
        visible: false,
        source: new XYZ({
          url: 'http://t4.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
          // tileGrid: tileGrid, // 指定切片的网格参数
        }),
      }),

    ],
    loading: true,
    searchText: '',
  },
  effects: {
    * changeBore({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'saveBore',
        payload: payload,
      });
      if (callback) callback();
    },
    * changeSearchText({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'saveSearchText',
        payload: payload,
      });
      if (callback) callback();
    },
    * changeMapType({ payload, callback }, { call, put, select }) {
      const state = yield select(state => state.pipe_home);//获取state中的数据
      if (payload === 'sensing') {
        state.layers[3].setVisible(false);
        state.layers[2].setVisible(true);
        state.layers[1].setVisible(false);
        state.layers[0].setVisible(true);
      } else if (payload === 'road') {
        state.layers[3].setVisible(true);
        state.layers[2].setVisible(false);
        state.layers[1].setVisible(true);
        state.layers[0].setVisible(false);
      }
      yield put({
        type: 'saveMapType',
        payload: payload,
      });
    },
    * changeCenterAndZoom({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'saveCenterAndZoom',
        payload: payload,
      });
    },
    * changeDesignCheckenKeys({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'saveDesignCheckenKeys',
        payload: payload,
      });
      setTimeout(function() {
        if (callback) callback();
      }, 0);
    },
    * changeAppendageCheckenKeys({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'saveAppendageCheckedKeys',
        payload: payload,
      });
      setTimeout(function() {
        if (callback) callback();
      }, 0);
    },
    * changeCharacteristicCheckenKeys({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'saveCharacteristicCheckedKeys',
        payload: payload,
      });
      setTimeout(function() {
        if (callback) callback();
      }, 0);
    },
    * changeShowMapType({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'saveShowMapType',
        payload: payload,
      });
    },
    * changePressLayerVisiable({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'savePressLayerVisiable',
        payload: payload,
      });
      setTimeout(function() {
        if (callback) callback();
      }, 0);
    },
    * changeWaterLayerVisiable({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'saveWaterLayerVisiable',
        payload: payload,
      });
      setTimeout(function() {
        if (callback) callback();
      }, 0);
    },
    * changeWorkstations1Visiable({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'saveWorkstations1Visiable',
        payload: payload,
      });
      setTimeout(function() {
        if (callback) callback();
      }, 0);
    },
    * changePipeLayerVisiable({ payload, callback }, { call, put, select }) {
      console.log('payload', payload);
      yield put({
        type: 'savePipeLayerVisiable',
        payload: payload,
      });
      setTimeout(function() {
        if (callback) callback();
      }, 0);
    },
    * changeDesignPipeLayerVisiable({ payload, callback }, { call, put, select }) {
      console.log('payload', payload);
      yield put({
        type: 'saveDesignPipeLayerVisiable',
        payload: payload,
      });
      setTimeout(function() {
        if (callback) callback();
      }, 0);
    },
    * changeHoleCoverLayerVisiable({ payload, callback }, { call, put, select }) {
      console.log('payload', payload);
      yield put({
        type: 'saveHoleCoverLayerVisiable',
        payload: payload,
      });
      setTimeout(function() {
        if (callback) callback();
      }, 0);
    },
    * changeReduceValveLayerVisiable({ payload, callback }, { call, put, select }) {
      console.log('payload', payload);
      yield put({
        type: 'saveReduceValveLayerVisiable',
        payload: payload,
      });
      setTimeout(function() {
        if (callback) callback();
      }, 0);
    },
    * reset({ payload, callback }, { call, put, select }) {
      console.log('reset=============');
      const state = yield select(state => state.pipe_home);//获取state中的数据
      yield put({
        type: 'resetData',
        payload: {
          pageLoaded: payload,
          data: state.data,
        },
      });
      if (callback) callback();
    },
    * changeLoaded({ payload, callback }, { call, put }) {
      yield put({
        type: 'changePageLoaded',
        payload: true,
      });
    },
    * fetchPointData({ payload, callback }, { call, put, select }) {
      console.log('fetchPointData');
      const state = yield select(state => state.pipe_home);//获取state中的数据
      const response = find(state.data, (o) => {
        return o.id === payload.id;
      });
      if (response) {
        yield put({
          type: 'savePointData',
          payload: { ...response.pressure_data, online_status: response.online_status },
        });
        if (callback) callback();
      }
    },
    * fetOneWorkstations1({ payload, callback }, { call, put, select }) {
      console.log('fetOneWorkstations1');
      const state = yield select(state => state.pipe_home);//获取state中的数据
      const response = find(state.Workstations1Data, (o) => {
        return o.id === payload.id;
      });
      console.log('response', response);
      if (response) {
        yield put({
          type: 'saveWorkstations1PointData',
          payload: {
            ...response,
            collected_at: (response.workstation_data.control_valve && response.workstation_data.control_valve[0]) ? response.workstation_data.control_valve[0].collected_at : '-',
            upstream_pressure: (response.workstation_data.control_valve && response.workstation_data.control_valve[0]) ? response.workstation_data.control_valve [0].parameters.upstream_pressure : '-',
            downstream_pressure: (response.workstation_data.control_valve && response.workstation_data.control_valve[0]) ? response.workstation_data.control_valve [0].parameters.downstream_pressure : '-',
            target_pressure: (response.workstation_data.control_valve && response.workstation_data.control_valve[0]) ? response.workstation_data.control_valve [0].parameters.target_pressure : '-',
            stroke: (response.workstation_data.control_valve && response.workstation_data.control_valve[0]) ? response.workstation_data.control_valve [0].parameters.stroke : '-',
            faqian: (response.workstation_data.sensor && response.workstation_data.sensor[0]) ? response.workstation_data.sensor [0].parameters.value : '-',
            fahou: (response.workstation_data.sensor && response.workstation_data.sensor[1]) ? response.workstation_data.sensor [1].parameters.value : '-',
          },
        });
        if (callback) callback();
      }
    },
    * fetOneWaterData({ payload, callback }, { call, put, select }) {
      console.log('fetOneWaterData');
      const state = yield select(state => state.pipe_home);//获取state中的数据
      const response = find(state.waterData, (o) => {
        return o.name === payload.name;
      });
      if (response) {
        yield put({
          type: 'saveWaterPointData',
          payload: response,
        });
        if (callback) callback();
      }
    },
    * fetchPipe({ payload, callback }, { call, put, select }) {
      const pipeResponse = yield call(queryPipe, payload);
      console.log('pipeResponse', pipeResponse);
      const state = yield select(state => state.pipe_home);//获取state中的数据
      const bore = state.bore === '全部' ? '' : state.bore;
      if (pipeResponse.status === 200) {
        if (typeof pipeResponse.data === 'string') {
          console.log('加载管网出错');
          message.error('加载现状管网出错');
          return false;
        }
        let newFeatures = [];
        if (bore) {
          for (let i = 0; i < pipeResponse.data.features.length; i++) {
            if (pipeResponse.data.features[i].properties['管径'] == bore) {
              newFeatures.push(pipeResponse.data.features[i]);
            }
          }
        } else {
          newFeatures = pipeResponse.data.features;
        }

        let newPipeResponse = {
          data: {
            ...pipeResponse.data,
            features: newFeatures,
          },
        };

        yield put({
          type: 'savePipe',
          payload: newPipeResponse.data,
        });

        if (callback) callback();
      }
    },
    * fetchDesignPipe({ payload, callback }, { call, put, select }) {
      const designPipeResponse = yield call(queryDesignPipe, payload);
      console.log('designPipeResponse', designPipeResponse);
      if (designPipeResponse.status === 200) {
        if (typeof designPipeResponse.data === 'string') {
          console.log('加载设计管网出错');
          message.error('加载设计管网出错');
          return false;
        }
        yield put({
          type: 'saveDesignPipe',
          payload: designPipeResponse.data,
        });

        if (callback) callback();
      }
    },
    * fetchHoleCover({ payload, callback }, { call, put, select }) {
      const HoleCoverResponse = yield call(queryHolecover, payload);
      console.log('HoleCoverResponse', HoleCoverResponse);

      if (HoleCoverResponse.status === 200) {
        if (typeof HoleCoverResponse.data === 'string') {
          console.log('加载井盖出错');
          message.error('加载井盖出错');
          return false;
        }
        yield put({
          type: 'saveHoleCover',
          payload: HoleCoverResponse.data,
        });

        if (callback) callback();
      }
    },
    * fetchReduceValve({ payload, callback }, { call, put, select }) {
      const ReduceValveResponse = yield call(queryReducevalve, payload);
      console.log('ReduceValveResponse', ReduceValveResponse);
      if (ReduceValveResponse.status === 200) {
        if (typeof ReduceValveResponse.data === 'string') {
          console.log('加载减压阀出错');
          message.error('加载减压阀出错');
          return false;
        }
        yield put({
          type: 'saveReduceValve',
          payload: ReduceValveResponse.data,
        });

        if (callback) callback();
      }
    },
    * fetchAppendageCharac({ payload, callback }, { call, put, select }) {
      const AppendageCharacResponse = yield call(queryAppendageCharac, payload);
      if (AppendageCharacResponse.status === 200) {
        if (typeof AppendageCharacResponse.data === 'string') {
          console.log('加载附属物特征出错');
          message.error('加载附属物特征出错');
          return false;
        }

        const state = yield select(state => state.pipe_home);//获取state中的数据
        const pipeData = state.pipeData;
        const searchText = state.searchText;
        let linePointArr = [];
        for (let i = 0; i < pipeData.features.length; i++) {
          for (let j = 0; j < pipeData.features[i].geometry.coordinates[0].length; j++) {
            linePointArr.push(pipeData.features[i].geometry.coordinates[0][j].toString());
          }
        }
        let newFeatures = [];
        for (let i = 0; i < AppendageCharacResponse.data.features.length; i++) {
          if (linePointArr.indexOf(AppendageCharacResponse.data.features[i].geometry.coordinates.toString()) >= 0 &&
             AppendageCharacResponse.data.features[i].properties['管点编号'].indexOf(searchText)>=0
          ) {
            newFeatures.push(AppendageCharacResponse.data.features[i]);
          }
        }

        let newAppendageCharacResponse = {
          data: {
            ...AppendageCharacResponse.data,
            features: newFeatures,
          },
        };

        yield put({
          type: 'saveAppendageCharac',
          payload: {
            key: payload.key,
            data: newAppendageCharacResponse.data,
          },
        });

        if (callback) callback();
      }
    },
    * fetch({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const state = yield select(state => state.pipe_home);//获取state中的数据
      payload = payload || state.searchParams;
      const workstations1Response = yield call(queryWorkstations1, payload);
      const response = yield call(query, payload);
      const waterResponse = yield call(queryWater, payload);

      if (response.data.status_code === 200) {
        yield put({
          type: 'save',
          payload: response.data,
        });
        yield put({
          type: 'saveWater',
          payload: waterResponse.data,
        });
        yield put({
          type: 'saveWorkstations1',
          payload: workstations1Response.data,
        });

        yield put({
          type: 'saveSearchParams',
          payload: payload,
        });

        yield put({
          type: 'changeLoading',
          payload: false,
        });
        if (callback) callback();
      }


    },
  },

  reducers: {
    saveBore(state, action) {
      return {
        ...state,
        bore: action.payload,
      };
    },
    saveSearchText(state, action) {
      console.log('action.payload',action.payload)
      return {
        ...state,
        searchText: action.payload,
      };
    },
    saveShowMapType(state, action) {
      return {
        ...state,
        showMapType: action.payload,
      };
    },
    saveDesignCheckenKeys(state, action) {
      return {
        ...state,
        designCheckedKeys: action.payload,
      };
    },
    saveAppendageCheckedKeys(state, action) {
      return {
        ...state,
        appendageCheckedKeys: action.payload,
      };
    },
    saveCharacteristicCheckedKeys(state, action) {
      return {
        ...state,
        characteristicCheckedKeys: action.payload,
      };
    },
    savePressLayerVisiable(state, action) {
      return {
        ...state,
        pressVisiable: action.payload,
      };
    },
    saveWaterLayerVisiable(state, action) {
      return {
        ...state,
        waterVisiable: action.payload,
      };
    },
    saveWorkstations1Visiable(state, action) {
      return {
        ...state,
        workstations1Visiable: action.payload,
      };
    },
    savePipeLayerVisiable(state, action) {
      console.log('action.payload', action.payload);
      return {
        ...state,
        pipeVisiable: action.payload,
      };
    },
    saveDesignPipeLayerVisiable(state, action) {
      console.log('action.payload', action.payload);
      return {
        ...state,
        designPipeVisiable: action.payload,
      };
    },
    saveHoleCoverLayerVisiable(state, action) {
      console.log('action.payload', action.payload);
      return {
        ...state,
        holeCoverVisiable: action.payload,
      };
    },
    saveReduceValveLayerVisiable(state, action) {
      console.log('action.payload', action.payload);
      return {
        ...state,
        reduceValveVisiable: action.payload,
      };
    },
    saveMapType(state, action) {
      return {
        ...state,
        mapType: action.payload,
      };
    },
    changeCenterAndZoom(state, action) {
      return {
        ...state,
        center: action.payload.center,
        zoom: action.payload.zoom,
      };
    },
    saveWater(state, action) {
      let parseWaterData = [{
        name: '园艺场沉沙池',
        data: {
          upload_time: action.payload.data.upload_time,
          item1: action.payload.data.item1,
          item2: action.payload.data.item2,
        },
        longitude: 88.9636,
        latitude: 43.1128,
      }, {
        name: '塔尔郎水厂',
        data: {
          upload_time: action.payload.data.upload_time,
          item3: action.payload.data.item3,
          item4: action.payload.data.item4,
          item5: action.payload.data.item5,
        },
        longitude: 89.06170232440421,
        latitude: 43.051727282747606,
      }, {
        name: '老城区水厂',
        data: {
          upload_time: action.payload.data.upload_time,
          item6: action.payload.data.item6,
          item7: action.payload.data.item7,
          item8: action.payload.data.item8,
        },
        longitude: 89.1777580614279,
        latitude: 42.989398853358125,
      }, {
        name: '示范区水厂',
        data: {
          upload_time: action.payload.data.upload_time,
          item9: action.payload.data.item9,
          item10: action.payload.data.item10,
        },

        longitude: 89.15627001722893,
        latitude: 43.010166270910275,
      }];
      return {
        ...state,
        waterData: parseWaterData,
      };
    },
    save(state, action) {
      for (let i = 0; i < action.payload.data.length; i++) {
        action.payload.data[i].my_time = String(Math.random() * 10);
      }
      return {
        ...state,
        data: action.payload.data,
        meta: action.payload.meta,
        additional: action.payload.additional,
      };
    },
    saveWorkstations1(state, action) {
      return {
        ...state,
        Workstations1Data: action.payload.data,
      };
    },
    savePipe(state, action) {
      let pipeLength = 0;
      for (let i = 0; i < action.payload.features.length; i++) {
        pipeLength += Number(action.payload.features[i].properties['长度'].toFixed(3));
      }
      return {
        ...state,
        pipeData: action.payload,
        pipeCount: action.payload.features.length,
        pipeLength: pipeLength.toFixed(2),
      };
    },
    saveDesignPipe(state, action) {
      return {
        ...state,
        designPipeData: action.payload,
      };
    },
    saveHoleCover(state, action) {
      return {
        ...state,
        holeCover: action.payload,
      };
    },
    saveReduceValve(state, action) {
      return {
        ...state,
        reduceValve: action.payload,
      };
    },
    saveAppendageCharac(state, action) {
      return {
        ...state,
        [action.payload.key]: action.payload.data,
      };
    },

    savePointData(state, action) {
      return {
        ...state,
        pointData: { ...action.payload, my_time: moment().format('YYYY-MM-DD HH:mm:ss') },
      };
    },
    saveWaterPointData(state, action) {
      return {
        ...state,
        waterPointData: { ...action.payload, my_time: moment().format('YYYY-MM-DD HH:mm:ss') },
      };
    },
    saveWorkstations1PointData(state, action) {
      return {
        ...state,
        workstations1PointData: { ...action.payload, my_time: moment().format('YYYY-MM-DD HH:mm:ss') },
      };
    },
    changePageLoaded(state, action) {
      return {
        ...state,
        pageLoaded: action.payload,
      };
    },
    resetData(state, action) {
      return {
        pageLoaded: action.payload.pageLoaded,
        bore: '全部',
        data: action.payload.data,
        pipeData: {},
        waterData: [],
        Workstations1Data: [],
        designPipeData: {},
        searchParams: {},
        holeCover: {},
        reduceValve: {},
        mapType: 'sensing',
        showMapType: true,
        pressVisiable: true,
        pipeVisiable: true,
        designPipeVisiable: true,
        workstations1Visiable: true,
        waterVisiable: true,
        zoom: 14,
        pointData: {},
        waterPointData: {},
        workstations1PointData: {},
        designCheckedKeys: ['design1'],
        appendageCheckedKeys: [],//附属物
        characteristicCheckedKeys: [],//特征
        center: [89.21655514667722, 42.96389386391127],
        layers: [
          new TileLayer({
            title: '天地图卫星影像',
            visible: true,
            source: new XYZ({
              url: 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
            }),
          }),
          new TileLayer({
            title: '天地图矢量图',
            visible: false,
            source: new XYZ({
              url: 'http://t3.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
            }),
          }),
          new TileLayer({
            title: '卫星标注',
            visible: true,
            source: new XYZ({
              url: 'http://t4.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
            }),
          }),
          new TileLayer({
            title: '矢量图标注',
            visible: false,
            source: new XYZ({
              url: 'http://t4.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=b45faf8590f42059eb14fc6065fc9606',
            }),
          }),

        ],
        loading: true,
        searchText: '',
      };
    },
  },

};
